﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Collections;

namespace ProgNetComponentsDx.Options.Design
{
    public class OptionGroupTypeConverter : ExpandableObjectConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
            {
                ConstructorInfo ci = null;
                OptionGroup g = (value as OptionGroup);
                OptionGroup[] children = g.ChildGroups.ToArray();

                Option[] options =  g.Options.ToArray();
                if (children != null && children.Length > 0)
                {
                    if (options != null && options.Length > 0)
                    {
                        ci = typeof(OptionGroup).GetConstructor(new Type[] { typeof(string), typeof(OptionGroup[]), typeof(Option[]) });
                        return new InstanceDescriptor(ci, new object[] { g.Name, children, options });
                    }
                    else
                    {
                        ci = typeof(OptionGroup).GetConstructor(new Type[] { typeof(string), typeof(OptionGroup[]) });
                        return new InstanceDescriptor(ci, new object[] { g.Name, children });
                    }
                }
                else
                {
                    if (options != null && options.Length > 0)
                    {
                        ci = typeof(OptionGroup).GetConstructor(new Type[] { typeof(string), typeof(Option[]) });
                        return new InstanceDescriptor(ci, new object[] { g.Name, options });
                    }
                    else
                    {
                        ci = typeof(OptionGroup).GetConstructor(new Type[] { typeof(string) });
                        return new InstanceDescriptor(ci, new object[] { g.Name });
                    }
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
